<template>
  <view class="pc-index-bg">
    <RemindWebSocket />
    <!-- 主容器：实现侧边栏与内容区圆角衔接 -->
    <view class="layout-container">
      <!-- 侧边栏由组件实现 -->
      <SideBar @tabChange="handleTabChange" />

      <!-- 主内容区 -->
      <view class="main-content">
        <!-- 头部标题 -->
        <view class="main-header">
          <el-icon class="back-btn" @click="onCancel"><ArrowLeft /></el-icon>
          <text class="main-title">{{ isEditMode ? '编辑提醒' : '新增提醒' }}</text>
        </view>
        <!-- 主体布局 -->
        <view class="main-body">
          <view class="remind-edit-container">
            <view class="remind-form">
              <!-- 提醒名称 -->
              <view class="form-item">
                <text class="form-label">提醒名称</text>
                <el-input 
                  v-model="form.name" 
                  placeholder="请输入提醒名称" 
                  maxlength="50" 
                  clearable 
                  style="width: 100%"
                  size="large"
                />
              </view>

              <!-- 重复方式 -->
              <view class="form-item">
                <text class="form-label">重复方式</text>
                <!-- 新的下拉选单 -->
                <el-select v-model="form.repeat" placeholder="请选择重复方式" style="width: 100%" size="large">
                  <el-option 
                    v-for="item in dictData.reminders_repeat_type" 
                    :key="item.dictCode" 
                    :label="item.dictLabel" 
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
                
                <!-- 注释掉原有的重复方式选择 -->
                <!--
                <view class="repeat-options">
                  <view 
                    v-for="option in repeatOptions" 
                    :key="option.value"
                    :class="['repeat-option', { active: form.repeat === option.value }]"
                    @click="form.repeat = option.value"
                  >
                    <text>{{ option.label }}</text>
                  </view>
                </view>
                -->
                
                <!-- 注释掉频率选择：仅每天/每周/每月显示 -->
                <!--
                <view v-if="form.repeat === 'daily'" class="frequency-row" style="margin-top: 16px; display: flex; align-items: center; gap: 8px;">
                  <text>每</text>
                  <el-select v-model="form.frequency" size="large" style="width: 80px;">
                    <el-option v-for="num in frequencyOptions" :key="num" :label="num" :value="num" />
                  </el-select>
                  <text>天</text>
                </view>
                <view v-else-if="form.repeat === 'weekly'" class="frequency-row" style="margin-top: 16px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                  <text>每</text>
                  <el-select v-model="form.frequency" size="large" style="width: 80px;">
                    <el-option v-for="num in frequencyOptions" :key="num" :label="num" :value="num" />
                  </el-select>
                  <text class="week-of-label">周的</text>
                  <el-select v-model="form.weekDays" multiple clearable placeholder="请选择周几" size="large" style="width: 310px;">
                    <el-option v-for="item in weekDayOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </view>
                <view v-else-if="form.repeat === 'monthly'" class="frequency-row" style="margin-top: 16px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                  <text>每</text>
                  <el-select v-model="form.frequency" size="large" style="width: 80px;">
                    <el-option v-for="num in frequencyOptions" :key="num" :label="num" :value="num" />
                  </el-select>
                  <text class="week-of-label">个月的</text>
                  <el-select v-model="form.monthDays" multiple clearable placeholder="请选择日期" size="large" style="width: 270px;">
                    <el-option v-for="num in monthDayOptions" :key="num" :label="num" :value="num" />
                  </el-select>
                  <text class="week-of-label">日</text>
                </view>
                -->
              </view>

              <!-- 提醒日期 -->
              <view class="form-item">
                <text class="form-label">提醒开始日期</text>
                <el-date-picker
                  v-model="form.date"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY年MM月DD日"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  size="large"
                />
              </view>

              <!-- 提醒时间 -->
              <view class="form-item">
                <text class="form-label">提醒时间</text>
                <el-time-picker
                  v-model="form.time"
                  placeholder="选择时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 100%"
                  size="large"
                />
              </view>

              <!-- 提醒内容 -->
              <view class="form-item">
                <text class="form-label">提醒内容</text>
                <el-input 
                  v-model="form.content" 
                  type="textarea" 
                  placeholder="请输入提醒内容" 
                  :rows="2" 
                  maxlength="100" 
                  show-word-limit
                  resize="none"
                  style="width: 100%"
                />
              </view>

              <!-- 语音提醒
              <view class="form-item">
                <text class="form-label">语音提醒</text>
                <view class="voice-upload-area">
                  <uni-icons type="microphone" size="48" color="#c0c4cc" />
                  <text class="upload-tip">点击录音或上传语音文件</text>
                  <button class="upload-btn" @click="uploadVoice">上传语音</button>
                </view>
              </view> -->

              <!-- 按钮组 -->
              <view class="btn-group">
                <el-button class="cancel-btn" @click="onCancel">取消</el-button>
                <el-button class="confirm-btn" type="primary" @click="onSave">确定</el-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期时间选择器 -->
    <!-- 移除模板中的uni-datetime-picker组件 -->

    <!-- 点击页面其他区域关闭菜单 -->
    <view 
      v-if="showSettingMenu" 
      class="menu-mask"
      @click="showSettingMenu = false"
    ></view>


  </view>
</template>

<script setup>
import { ref, reactive, watch, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { ArrowLeft } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import { go } from '@/utils/nav.js';
import SideBar from '/pages/pc/sideBar.vue';
import { getDictData, addReminder, updateReminder } from '@/api/pc/elderly';
import { useUserStore } from '@/store/modules/user';
import { useReminderEditStore } from '@/store/modules/reminder.js';
import RemindWebSocket from '@/components/RemindWebSocket.vue'; 

const route = useRoute();
const userStore = useUserStore();
const reminderEditStore = useReminderEditStore();
const showSettingMenu = ref(false);

// 判断是否为编辑模式
const isEditMode = ref(false);
const reminderId = ref(null);

// 字典数据
const dictData = reactive({
  reminders_repeat_type: []
});

// 表单数据
const form = reactive({
  name: '', // 对应API的title
  date: '', // 对应API的nextTrigger
  time: '', // 对应API的time
  repeat: '', // 对应API的repeatType
  frequency: 1, // 新增频率字段，默认1
  weekDays: [], // 新增每周几字段
  monthDays: [], // 新增每月几号字段
  content: '', // 对应API的description
  voiceFile: ''
});

// 重复选项 - 注释掉，改为使用字典数据
/*
const repeatOptions = ref([
  { label: '单次', value: 'once' },
  { label: '每天', value: 'daily' },
  { label: '每周', value: 'weekly' },
  { label: '每月', value: 'monthly' }
]);
*/

// 频率选项数组
const frequencyOptions = Array.from({ length: 99 }, (_, i) => i + 1);

// 每周几选项
const weekDayOptions = ref([
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]);

// 每月几号选项
const monthDayOptions = Array.from({ length: 31 }, (_, i) => i + 1);

// 自动推算最近的提醒开始日期 - 注释掉，因为现在使用字典数据
/*
watch([
  () => form.repeat,
  () => form.frequency,
  () => form.weekDays.slice(),
  () => form.monthDays.slice()
], () => {
  if (form.repeat === 'once') return;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  let nextDate = '';

  if (form.repeat === 'daily') {
    // 每frequency天
    nextDate = formatDate(today);
  } else if (form.repeat === 'weekly' && form.weekDays.length > 0) {
    // 每frequency周的 weekDays
    const week = today.getDay() === 0 ? 7 : today.getDay(); // 1=周一, 7=周日
    let minDiff = Infinity;
    let candidate = null;
    for (let i = 0; i < 7 * form.frequency; i++) {
      const d = new Date(today.getTime() + i * 24 * 60 * 60 * 1000);
      const w = d.getDay() === 0 ? 7 : d.getDay();
      if (form.weekDays.includes(w)) {
        if (i < minDiff) {
          minDiff = i;
          candidate = d;
        }
      }
    }
    if (candidate) nextDate = formatDate(candidate);
  } else if (form.repeat === 'monthly' && form.monthDays.length > 0) {
    // 每frequency月的 monthDays
    const y = today.getFullYear();
    const m = today.getMonth();
    let found = false;
    for (let addMonth = 0; addMonth < 12; addMonth += form.frequency) {
      const baseMonth = m + addMonth;
      const baseYear = y + Math.floor(baseMonth / 12);
      const realMonth = (baseMonth % 12 + 12) % 12;
      for (const d of form.monthDays) {
        const candidate = new Date(baseYear, realMonth, d);
        if (candidate >= today && candidate.getMonth() === realMonth) {
          nextDate = formatDate(candidate);
          found = true;
          break;
        }
      }
      if (found) break;
    }
  }
  if (nextDate) form.date = nextDate;
});
*/

// 监听重复方式变化，重置相关字段 - 注释掉，因为现在使用字典数据
/*
watch(() => form.repeat, (val) => {
  form.frequency = 1;
  form.weekDays = [];
  form.monthDays = [];
  form.date = '';
  form.time = '';
});
*/

function formatDate(date) {
  const y = date.getFullYear();
  const m = (date.getMonth() + 1).toString().padStart(2, '0');
  const d = date.getDate().toString().padStart(2, '0');
  return `${y}-${m}-${d}`;
}

// 不再通过路由参数判断，改为使用 store；保留空占位
const unwatchRoute = () => {};

// 页面加载时获取字典数据和填充表单
onMounted(async () => {
  try {
    // 获取重复方式字典数据
    const repeatTypeResponse = await getDictData('reminders_repeat_type');
    if (repeatTypeResponse.code === 200 && repeatTypeResponse.data) {
      dictData.reminders_repeat_type = repeatTypeResponse.data;
      console.log('重复方式字典数据加载完成:', dictData.reminders_repeat_type);
    }

    // 检查是否有编辑参数
    const data = reminderEditStore.data;
    if (data && data.id) {
      isEditMode.value = true;
      reminderId.value = data.id;
      form.name = data.title || '';
      form.content = data.description || '';
      // 统一时间格式为 HH:mm，去掉秒数
      form.time = data.time ? data.time.substring(0, 5) : '';
      form.repeat = data.repeatType || '';
      form.date = data.nextTrigger || data.baseDate || '';
      console.log('编辑模式（来自store）:', data);
    } else {
      isEditMode.value = false;
      clearForm();
      await nextTick();
      console.log('新增模式（store无数据）');
    }
  } catch (error) {
    console.error('获取字典数据失败:', error);
  }
});

// 组件卸载时清理监听器
onBeforeUnmount(() => {
  unwatchRoute();
});

// 清空表单数据的函数
const clearForm = () => {
  Object.assign(form, {
    name: '',
    content: '',
    time: '',
    repeat: '',
    date: '',
    frequency: 1,
    weekDays: [],
    monthDays: [],
    voiceFile: ''
  });
};

// 处理侧边栏tab切换
const handleTabChange = (tab) => {
  if (tab === 'home') {
  go('/pages/pc/index');
  } else if (tab === 'remind') {
    // 跳转到提醒列表页面
  go('/pages/pc/remind');
  }
};


// 上传语音
const uploadVoice = () => {
  uni.chooseFile({
    count: 1,
    type: 'audio',
    success: (res) => {
      form.voiceFile = res.tempFilePaths[0];
      uni.showToast({ title: '语音上传成功', icon: 'success' });
    }
  });
};

// 取消：直接跳提醒列表，避免多次进入后 navigateBack 无历史仅刷新当前页
const onCancel = () => {
  clearForm();
  reminderEditStore.clear();
  go('/pages/pc/remind', { replace: true });
};

// 保存
const onSave = async () => {
  // 表单验证
  if (!form.name.trim()) {
    return uni.showToast({ title: '请输入提醒名称', icon: 'none' });
  }
  if (!form.date) {
    return uni.showToast({ title: '请选择提醒日期', icon: 'none' });
  }
  if (!form.time) {
    return uni.showToast({ title: '请选择提醒时间', icon: 'none' });
  }
  if (!form.content.trim()) {
    return uni.showToast({ title: '请输入提醒内容', icon: 'none' });
  }

  try {
    uni.showLoading({ title: '保存中...' });

    // 准备提交数据
    const submitData = {
      id: isEditMode.value ? reminderId.value : null,
      userId: userStore.id,
      title: form.name,
      description: form.content,
      time: form.time,
      repeatType: form.repeat,
      nextTrigger: form.date
    };

    console.log('提交数据:', submitData);

    let response;
    if (isEditMode.value) {
      // 修改提醒
      response = await updateReminder(submitData);
      console.log('修改提醒响应:', response);
    } else {
      // 新增提醒
      response = await addReminder(submitData);
      console.log('新增提醒响应:', response);
    }

    uni.hideLoading();

    if (response.code === 200) {
      uni.showToast({ 
        title: isEditMode.value ? '修改成功' : '新增成功', 
        icon: 'success' 
      });
      setTimeout(() => {
  reminderEditStore.clear();
  go('/pages/pc/remind', { replace: true });
      }, 1200);
    } else {
      uni.showToast({ 
        title: response.msg || '保存失败', 
        icon: 'none' 
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存提醒失败:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
};
</script>

<style scoped>
/* 主容器样式 */
.layout-container {
  display: flex;
  height: 100vh;
  background-color: #1976ed; 
  border-radius: 0;
  overflow: hidden;
  position: relative; 
  align-items: stretch;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 24px 0 0 24px;
  overflow: hidden;
}

.main-header {
  height: 64px;
  display: flex;
  align-items: center;
  padding-left: 32px;
  background: #fff;
  font-size: 28px;
  font-weight: 600;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.back-btn {
  font-size: 28px;
  color: #222;
  cursor: pointer;
  margin-right: 16px;
  font-weight: 700;
}

.main-title {
  color: #222;
}

.main-body {
  flex: 1;
  background: #fff;
  padding: 32px 20px;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  overflow-y: auto;
  min-height: 0;
}

/* 提醒编辑容器样式 */
.remind-edit-container {
  background: #fff;
  border-radius: 0;
  padding: 32px 40px;
  box-shadow: none;
  width: 100%;
  max-width: 550px;
}

.remind-form {
  margin-top: 0;
}

.form-item {
  margin-bottom: 28px;
}

.form-label {
  font-size: 18px;
  color: #222;
  margin-bottom: 12px;
  display: block;
  font-weight: 600;
}



/* 时间输入区域 */
.time-input-wrap {
  display: flex;
  gap: 16px;
}

.time-input {
  flex: 1;
}

/* 重复选项样式 */
.repeat-options {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.repeat-option {
  padding: 8px 16px;
  border: 1px solid #e3e7ed;
  border-radius: 6px;
  background: #fff;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.repeat-option.active {
  background: #1976ed;
  color: #fff;
  border-color: #1976ed;
}

/* 频率选择行样式 */
.frequency-row {
  margin-top: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
.frequency-row .week-of-label {
  white-space: nowrap;
  margin: 0 4px;
}

/* 文本域样式 */
.textarea-wrap {
  position: relative;
  border: 1px solid #e3e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
}

.textarea {
  width: 100%;
  border: none;
  background: transparent;
  font-size: 16px;
  outline: none;
  resize: none;
  min-height: 50px;
  height: 50px;
  padding: 4px 0;
  line-height: 1.2;
}

.char-count {
  position: absolute;
  bottom: 8px;
  right: 12px;
  font-size: 12px;
  color: #999;
}

/* 语音上传区域 */
.voice-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 1px dashed #c0c4cc;
  border-radius: 8px;
  gap: 15px;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
  text-align: center;
}

.upload-btn {
  background: #1976ed;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

/* 按钮组样式 */
.btn-group {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 80px;
}

.cancel-btn {
  background: #fff;
  color: #888;
  border: 1px solid #e3e7ed;
  border-radius: 8px;
  font-size: 16px;
  padding: 0 32px;
  height: 40px;
  cursor: pointer;
}

.confirm-btn {
  background: #1976ed;
  color: #fff;
  border-radius: 8px;
  font-size: 16px;
  padding: 0 32px;
  height: 40px;
  border: none;
  cursor: pointer;
  font-weight: 600;
}

/* 点击页面其他区域关闭菜单 */
.menu-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: transparent;
  z-index: 5;
}

/* Element Plus 输入框样式覆盖 */
:deep(.el-input) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  height: 44px !important;
  border: 1px solid #e3e7ed !important;
  border-radius: 8px !important;
  background: #fff !important;
  box-shadow: none !important;
  padding: 0 16px !important;
}

:deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff !important;
}

:deep(.el-input__inner) {
  height: 44px !important;
  line-height: 44px !important;
  font-size: 16px !important;
  border: none !important;
  background: transparent !important;
  padding: 0 !important;
}

:deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-time-picker) {
  width: 100%;
}

:deep(.el-date-editor .el-input__wrapper) {
  height: 44px !important;
  border: 1px solid #e3e7ed !important;
  border-radius: 8px !important;
  background: #fff !important;
  box-shadow: none !important;
  padding: 0 16px !important;
}

:deep(.el-time-picker .el-input__wrapper) {
  height: 44px !important;
  border: 1px solid #e3e7ed !important;
  border-radius: 8px !important;
  background: #fff !important;
  box-shadow: none !important;
  padding: 0 16px !important;
}

:deep(.el-date-editor .el-input__inner) {
  height: 44px !important;
  line-height: 44px !important;
  font-size: 16px !important;
  border: none !important;
  background: transparent !important;
  padding: 0 !important;
}

:deep(.el-time-picker .el-input__inner) {
  height: 44px !important;
  line-height: 44px !important;
  font-size: 16px !important;
  border: none !important;
  background: transparent !important;
  padding: 0 !important;
}

:deep(.el-textarea__inner) {
  border: 1px solid #e3e7ed !important;
  border-radius: 8px !important;
  background: #fff !important;
  box-shadow: none !important;
  padding: 16px !important;
  font-size: 16px !important;
  resize: none !important;
  min-height: 80px !important;
}

:deep(.el-input__suffix) {
  height: 44px;
  line-height: 44px;
}

:deep(.el-input__suffix-inner) {
  height: 44px;
  line-height: 44px;
}

/* Element Plus 下拉选择框样式覆盖 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  height: 44px !important;
  border: 1px solid #e3e7ed !important;
  border-radius: 8px !important;
  background: #fff !important;
  box-shadow: none !important;
  padding: 0 16px !important;
}

:deep(.el-select .el-input__inner) {
  height: 44px !important;
  line-height: 44px !important;
  font-size: 16px !important;
  border: none !important;
  background: transparent !important;
  padding: 0 !important;
}

:deep(.el-select .el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
}

:deep(.el-select .el-input__wrapper.is-focus) {
  border-color: #409eff !important;
}

/* Element Plus 文本域样式覆盖 */
:deep(.el-textarea) {
  width: 100%;
}

:deep(.el-textarea .el-textarea__inner) {
  border: 1px solid #e3e7ed !important;
  border-radius: 8px !important;
  background: #fff !important;
  font-size: 16px !important;
  padding: 16px !important;
  line-height: 1.2 !important;
  min-height: 80px !important;
  resize: none !important;
}

:deep(.el-textarea .el-textarea__inner:hover) {
  border-color: #c0c4cc !important;
}

:deep(.el-textarea .el-textarea__inner:focus) {
  border-color: #409eff !important;
}

:deep(.el-input__count) {
  background: transparent !important;
  right: 8px !important;
  bottom: 8px !important;
}

/* 移除原有的字符计数样式 */
.char-count {
  display: none;
}


</style> 
